/*
 * @Description: 
 * @Author: duan_shuangjun 丶
 * @Date: 2025-08-20 20:51:00
 * @LastEditTime: 2025-08-20 20:51:41
 */
/*
    金额/数值精度处理工具，与旧项目保持命名兼容
*/

// 转字符串保留两位小数（仅保留数字和一个小数点）
export function strNumberToFixed(input: string | number, digits = 2): string {
    const str = String(input ?? '')
    // 仅保留数字和小数点
    let sanitized = str.replace(/[^\d.]/g, '')
    // 只能一个小数点
    const firstDot = sanitized.indexOf('.')
    if (firstDot !== -1) {
        sanitized = sanitized.slice(0, firstDot + 1) + sanitized.slice(firstDot + 1).replace(/\./g, '')
    }
    if (!sanitized) return ''
    const n = Number(sanitized)
    if (Number.isNaN(n)) return ''
    return n.toFixed(digits)
}

// 使用十进制字符串规避浮点误差
function toInteger(num: number) {
    const s = num.toString()
    if (s.indexOf('.') < 0) return { int: num, pow: 1 }
    const len = s.length - s.indexOf('.') - 1
    return { int: Number(s.replace('.', '')), pow: Math.pow(10, len) }
}

export function mathAdd(a: number, b: number): number {
    const x = toInteger(a)
    const y = toInteger(b)
    const pow = Math.max(x.pow, y.pow)
    return (a * pow + b * pow) / pow
}

export function mathSubtract(a: number, b: number): number {
    const x = toInteger(a)
    const y = toInteger(b)
    const pow = Math.max(x.pow, y.pow)
    return (a * pow - b * pow) / pow
}

export function mathMultiply(a: number, b: number): number {
    const x = toInteger(a)
    const y = toInteger(b)
    return (x.int * y.int) / (x.pow * y.pow)
}

export function mathDivide(a: number, b: number): number {
    const x = toInteger(a)
    const y = toInteger(b)
    return (x.int / y.int) * (y.pow / x.pow)
}
